import { ref } from 'vue'
import { defineStore } from 'pinia';
import { GetUserInfoApi } from '@/service/index.js'
import { useCommStore, useCartStore } from '@/store/index.js'
export const useUserStore = defineStore('userStore', () => {
	const member = ref() // 登陆成功返回的用户信息
	const token = ref('') // token 信息
	const userInfo = ref({ // 用户信息
		id: '', //ID
		avatar: "", //头像
		name: "", //昵称
		mobile: '', // 手机号
		create_time: "", //注册时间
		shop_id: '', //商家ID
		is_shop: 0, //==1是商家  ==2商家所有的功能被禁用 ==0不是商家
		is_dai: 0, //==1是代理 ==0不是代理
		rider: 0, //==1是骑手 ==0不是骑手
		member: {
			order_refund_ratio: "", //退货率
			order_refund_num: '', //退货订单数量
			avatar: "",
			id: ''
		}
	})
	const rememberMe = ref({
		mobile: '',
		loginpass: ''
	})
	const SETREMEMBERME = (info) => {
		rememberMe.value = info
	}
	const SETMEMBER = (info) => {
		member.value = info.member
		token.value = info.token.access_token
		GETUSERINFO()
	}
	// 获取用户信息
	const GETUSERINFO = () => {
		let params = {
			name: member.value.name,
			avatar: ''
		}
		GetUserInfoApi(params).then(res => {
			userInfo.value = res.data
		})
	}
	const SETLATLONINFO = (info) => {
		console.log(info, 'SETLATLONINFO');
	}
	const LOGOUT = () => {
		const { CLEARCARTLIST } = useCartStore()
		member.value = {}
		userInfo.value = {}
		token.value = ''
		CLEARCARTLIST()
		uni.redirectTo({
			url: '/pages/login/login'
		})
	}
	return {
		member,
		token,
		userInfo,
		rememberMe,
		SETMEMBER,
		GETUSERINFO,
		SETREMEMBERME,
		LOGOUT
	}
}, {
  // 数据持久化
	persist: {
		storage: {
			getItem: (key) => {
			  return uni.getStorageSync(key)
			},
			setItem: (key, value) => {
			  return uni.setStorageSync(key, value)
			},
		}
	}
})
